package com.ruoyi.common.utils.secret;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil
{
    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);

    public final static String GEN_ENCODE_RULE = "HHKJ0okmNJI(hhkj";

    /**
     * AES加密
     *
     * @param content 内容
     * @return 加密文本
     */
    public static String encrypt(String content)
    {
        return encrypt(content, GEN_ENCODE_RULE);
    }

    /**
     * AES加密
     *
     * @param content    内容
     * @param encodeRule 编码规则
     * @return 加密文本
     */
    public static String encrypt(String content, String encodeRule)
    {
        try {
            byte[] bytes = encodeRule.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] bytes1 = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(bytes1);

        } catch (Exception e) {
            LOGGER.error("AES编码异常", e);
        }
        return null;
    }

    /**
     * 内容解码
     *
     * @param content    内容信息
     * @param encodeRule 解码密钥
     * @return 具体内容
     */
    public static String decrypt(String content, String encodeRule)
    {
        byte[] decode = Base64.getDecoder().decode(content);
        try {
            SecretKeySpec keySpec = new SecretKeySpec(encodeRule.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] bytes = cipher.doFinal(decode);
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            LOGGER.error("AES解码异常", e);
        }
        return null;
    }


}
